<?php

namespace App\Http\Controllers\System;



use App\Model\System\NoticeConfig;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Laravel\Lumen\Routing\Controller as BaseController;
use App\Http\Controllers\MessagePacket;

class NoticeController extends BaseController
{
    use MessagePacket;


    function get(Request $request, $type, $uid)
    {
        try{
            $objs = NoticeConfig::where('utype', $type)->where('uid', $uid)->get()->toarray();
            if(empty($objs)){
                $obj = new NoticeConfig(['utype'=>$type, 'uid'=>$uid, 'ntype'=>1]);
                $obj->save();
                $obj2 = new NoticeConfig(['utype'=>$type, 'uid'=>$uid, 'ntype'=>2]);
                $obj2->save();
                $objs = NoticeConfig::where('utype', $type)->where('uid', $uid)->get()->toarray();
            }
            return $this->success($objs);
        }catch (\Exception $e){
            return $this->fail(false, $e->getMessage());
        }
    }


    /**
     * @param $request
     * @param $type
     * @param $uid
     * @return  array
     */
    function set(Request $request, $type, $uid)
    {
        try{
            if(!$request->has('configs')){
                throw new \Exception('q缺少参数');
            }

            $configs = $request->get('configs');

            foreach ($configs as $cfg){
                if(!empty($cfg['id'])){
                    $obj = NoticeConfig::find($cfg['id']);
                    $obj->update($cfg);
                    $obj->save();
                }else{
                    unset($cfg['id']);
                    $obj = new NoticeConfig($cfg);
                    $obj->save();
                }
            }
            return $this->success(true);
        }catch (\Exception $e){
            throw  $e;
            return $this->fail(false, $e->getMessage());
        }
    }

}
